package instantHelper.NormalMode;

import instantHelper.Models.CustomHttpClient;
import instantHelper.Raceway.DbHelper;
import instantHelper.Raceway.FTPHelper;
import instantHelper.Raceway.InstantHelperConstant;
import instantHelper.Raceway.R;
import instantHelper.Raceway.SettingsUtil;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class NormalModeVideoCapture extends Activity implements
		OnClickListener, SurfaceHolder.Callback {
	MediaRecorder recorder;
	SurfaceHolder holder;
	private static final String TAG = NormalModeVideoCapture.class.getSimpleName();
	boolean recording = false;
	private String fileName;
	private String fileNameForHTTP;
	private int videoCount = 0;
	ArrayList<String> videoPaths = new ArrayList<String>();
	String androidId;
	static String requestId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		androidId = SettingsUtil.getAndroidID(getApplicationContext());
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			requestId = extras.getString("requestId");
		}


		MyLocationListener.getGPSData(getApplicationContext(), androidId,
				requestId);
		setContentView(R.layout.normalmode_video);
		recorder = new MediaRecorder();
		createPicturePaths(androidId, requestId);
		// initRecorder();
		SurfaceView cameraView = (SurfaceView) findViewById(R.id.CameraView);
		holder = cameraView.getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

		cameraView.setClickable(true);
		// cameraView.setOnClickListener(this);
	}

	private void initRecorder() {
		recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
		recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
		String videoQuality = SettingsUtil
				.getVideoQuality(getApplicationContext());
		CamcorderProfile cpHigh;
		if (videoQuality.equalsIgnoreCase("Low")) {
			cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
		} else if (videoQuality.equalsIgnoreCase("High")) {
			cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
		} else {
			cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
		}

		recorder.setProfile(cpHigh);
		recorder.setOutputFile(fileName);
		int maxDuration = Integer.parseInt(SettingsUtil
				.getVideoMaximumDuration(getApplicationContext()));
		recorder.setMaxDuration(maxDuration * 1000); // 50 seconds
		recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
	}

	private void prepareRecorder() {
		recorder.setPreviewDisplay(holder.getSurface());
		try {
			recorder.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
			finish();
		} catch (IOException e) {
			e.printStackTrace();
			finish();
		}
	}

	public void onClick(View v) {
		Button videoButton = (Button) findViewById(R.id.buttonRecordVideo);
		if (recording) {
			recorder.stop();
			videoButton.setText("Start Recording");
			recording = false;
			try {
				sendVideoRequestToCentralApp();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// Let's initRecorder so we can record again
			createPicturePaths(androidId, requestId);

		} else {
			initRecorder();
			prepareRecorder();
			videoButton.setText("Stop Recording");
			recording = true;
			recorder.start();
		}
	}

	public void surfaceCreated(SurfaceHolder holder) {

	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		if (recording) {
			recorder.stop();
			recording = false;
		}
		recorder.release();
		finish();
	}

	@Override
	public void onClick(DialogInterface arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	protected String createPicturePaths(String androidId, String requestId) {
		fileName = "ihcenterapp/videos/video_" + androidId + "_" + requestId
				+ "_" + videoCount + ".mp4";
		fileNameForHTTP = "video_" + androidId + "_" + requestId + "_"
				+ videoCount + ".mp4";
		fileName = sanitizePath(fileName);
		// make sure the directory we plan to store the recording in exists
		File directory = new File(fileName).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		videoCount++;
		videoPaths.add(fileName);
		return fileName;
	}

	protected String sanitizePath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.contains(".")) {
			path += ".mp4";
		}
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ path;
	}

	private String sendVideoRequestToCentralApp() throws IllegalStateException,
			IOException, URISyntaxException {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newVideo";

		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters
				.add(new BasicNameValuePair("videoPath", fileNameForHTTP));
		postParameters.add(new BasicNameValuePair("requestId", requestId));
		postParameters.add(new BasicNameValuePair("androidId", androidId));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("result");
			Context context = getApplicationContext();

			if (result.equalsIgnoreCase("successfull")) {
				sendVideoFileViaFTP(fileName);
			}

		} catch (Exception e) {

		}
		return result;
	}

	protected void sendVideoFileViaFTP(String fileName2) {
		boolean issend = FTPHelper.sendToServer(fileName2, "videos/");
		if (issend) {
			if (SettingsUtil.getDeleteDataControl(getApplicationContext())) {
				SettingsUtil.deleteFile(fileName2);
			}
		} else {
			ContentValues contentValues = new ContentValues();
			Date time = new Date();
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_DATE,
					time.toString());
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_ISSEND, false);
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_PATH,
					fileName2);
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_REQUEST_ID,
					requestId);
			contentValues.put(InstantHelperConstant.DB_DIRECTORY_TYPE, "video");
			// update
			DbHelper myDbHelper1 = new DbHelper(this);
			SQLiteDatabase db1 = myDbHelper1.getWritableDatabase();
			db1.insert(InstantHelperConstant.DB_DIRECTORY_TABLE, null,
					contentValues);

		}

	}


}
